package org.wh1tew0lf.vframe.framework;

import java.util.Map;

import org.wh1tew0lf.vframe.framework.vframeexception.VDBFieldNameMapIsNullException;
import org.wh1tew0lf.vframe.framework.vframeexception.VFieldNameIsNullException;
import org.wh1tew0lf.vframe.framework.vframeexception.VFieldNotFoundException;
import org.wh1tew0lf.vframe.framework.vframeexception.VFrameException;
import org.wh1tew0lf.vframe.framework.vframeexception.VOutOfBoundaryException;

public class AbstractDatabaseOperator {

	protected static String toString(boolean rawValueData, String formatText, String seperator,
			String fieldName, Map<String, String> fieldNameMap,
			IDatabaseRestriction... restrictions) throws VFrameException {
		String result = formatText;
		boolean isValueArray = (result.indexOf("##VALUES##") >= 0);
		boolean hasValue = (result.indexOf("##VALUE") >= 0);
		boolean hasField = (result.indexOf("##FIELD##") >= 0);
		boolean hasFieldValue = (result.indexOf("##FIELD_VALUE##") >= 0);
		if (hasFieldValue) {
			if (fieldName == null) {
				throw new VFieldNameIsNullException();
			}
			if (fieldNameMap == null) {
				throw new VDBFieldNameMapIsNullException();
			}
			String dbFieldName = fieldNameMap.get(fieldName);
			if (dbFieldName == null) {
				throw new VFieldNotFoundException(fieldName);
			}
			result = result.replace("##FIELD_VALUE##", dbFieldName);
		}
		if (hasField) {
			if (fieldName == null) {
				throw new VFieldNameIsNullException();
			}
			if (fieldNameMap == null) {
				throw new VDBFieldNameMapIsNullException();
			}
			result = result.replace("##FIELD##", fieldName);
		}
		if (hasValue) {
			if (isValueArray) {
				StringBuffer valueStringBuffer = new StringBuffer();
				for (int i = 0; i < restrictions.length; i++) {
					valueStringBuffer.append(restrictions[i]
							.toString(rawValueData, fieldNameMap));
					valueStringBuffer.append(seperator);
				}
				String valueString = valueStringBuffer.substring(0,
						valueStringBuffer.length() - seperator.length());
				result = result.replace("##VALUES##", valueString);
			} else {
				int nextValuePos = result.indexOf("##VALUE_");
				int valueLength = restrictions.length;
				while (nextValuePos > -1) {
					String replaceText = result.substring(nextValuePos,
							nextValuePos + 11);
					String replaceIndexString = replaceText.substring(8, 9);
					Number replaceIndex = Integer.parseInt(replaceIndexString,
							Character.MAX_RADIX);
					if (valueLength <= replaceIndex.intValue()) {
						throw new VOutOfBoundaryException(
								replaceIndex.intValue(), valueLength,
								restrictions);
					}
					String replacement = restrictions[replaceIndex.intValue()]
							.toString(rawValueData, fieldNameMap);
					result = result.replace(replaceText, replacement);
					nextValuePos = result.indexOf("##VALUE_");
					replaceText = null;
					replaceIndexString = null;
					replaceIndex = null;
					replacement = null;
				}
			}
		}
		return result;
	}

}
